﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using SergeyPravodelov.Practice.BookStore.Data.Model;

namespace SergeyPravodelov.Practice.BookStore.Data.Services
{
    public class InMemoryDataService : IDataService
    {
        private static readonly object SyncRoot = new object();
        private readonly Dictionary<int, Entity> _storage = new Dictionary<int, Entity>();
        private int _identity = 0;

        public IEnumerable<Entity> GetData()
        {
            lock (SyncRoot)
            {
                return _storage.Select(f => f.Value);
            }
        }

        public Entity GetData(int id)
        {
            lock (SyncRoot)
            {
                return _storage.ContainsKey(id) ? _storage[id] : null;
            }
        }

        public int PutData(Entity entity)
        {
            lock (SyncRoot)
            {
                entity.Id = ++_identity;
                _storage.Add(entity.Id, entity);
                return entity.Id;
            }
        }

        public void RemoveData(int id)
        {
            lock (SyncRoot)
            {
                if (_storage.ContainsKey(id))
                {
                    _storage.Remove(id);
                }
            }
        }

        public void ModifyData(Entity entity)
        {
            lock (SyncRoot)
            {
                if (_storage.ContainsKey(entity.Id))
                {
                    _storage[entity.Id] = entity;
                }
            }
        }

        public IEnumerable<int> PutData(IEnumerable bulk)
        {
            return bulk.Cast<Entity>().ToList().Select(PutData);
        }
    }
}
